﻿package idv.cjcat.emitter.deflectors {
	use namespace engine;
	
	import idv.cjcat.emitter.*;
	import idv.cjcat.emitter.ds.*;
	import idv.cjcat.emitter.geom.*;
	
	/**
	 * Line-shaped deflector.
	 */
	public class LineDeflector extends Deflector {
		
		public var x:Number;
		public var y:Number;
		public var normal:Vector2D = new Vector2D(0, -1);
		
		public function LineDeflector(x:Number = 0, y:Number = 0) {
			this.x = x;
			this.y = y;
		}
		
		override public function getMotionData4D(pd:ParticleData):MotionData4D {
			//normal dispacement
			var r:Vector2D = new Vector2D(pd.cx - x, pd.cy - y);
			r = r.project(normal);
			
			//no collision detected
			if (r.dot(normal) >= 0) return new MotionData4D(pd.cx, pd.cy, pd.vx, pd.vy);
			
			//collision detected
			var v:Vector2D = new Vector2D(pd.vx, pd.vy);
			v = v.project(normal);
			return MotionData4DPool.get(pd.cx - r.x, pd.cy - r.y, pd.vx - v.x * bounce * 2, pd.vy - v.y * bounce * 2);
		}
		
		
		//XML
		//------------------------------------------------------------------------------------------------
		
		override public function toXML():XML {
			var xml:XML = super.toXML();
			xml.@type = DeflectorType.LINE;
			xml.@x = x.toString();
			xml.@y = y.toString();
			xml.@normalX = normal.x.toString();
			xml.@normalY = normal.y.toString();
			
			return xml;
		}
		override public function parseXML(xml:XML):void {
			super.parseXML(xml);
			
			x = parseFloat(xml.@x);
			y = parseFloat(xml.@y);
			normal.set(parseFloat(xml.@normalX), parseFloat(xml.@normalY));
		}
		
		//------------------------------------------------------------------------------------------------
		//end of XML
	}
}